<?php

/**
 * @package Core
 */
class Core_Context {
    const AFTER_DISPATCH = 'after_dispatch';

    public static $response;
    public static $sapi;

    protected static $hooks = array();

    private function __construct() {

    }

    public static function register($name, callable $func) {
        if (!isset(self::$hooks[$name])) {
            self::$hooks[$name] = array();
        }
        self::$hooks[$name][] = $func;
    }

    public static function trigger($name) {
        if (isset(self::$hooks[$name])) {
            foreach (self::$hooks[$name] as $func) {
                call_user_func($func);
            }
        }
    }

    /**
     * internal api call
     * change current cmd to $cmd
     * merge $params to current params
     * and restore environment after get result
     *
     * @param $cmd
     * @param array $params
     * @return mixed
     */
    public static function call($cmd, $params = []) {
        $req = Core_Request::getInstance();
        $cmd_bak = $req->getCmd();
        $params_bak = $req->getParams();

        $req->setCmd($cmd);
        $req->addParams($params);
        $ret = Core_Dispatcher::runCgi();

        //restore context
        $req->setCmd($cmd_bak);
        $req->setParams($params_bak);

        return $ret;
    }
} 
